package com.spyx.acl.service.impl;

import com.atyx.spyx.model.acl.AdminRole;
import com.atyx.spyx.model.acl.Role;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spyx.acl.mapper.AdminRoleMapper;
import com.spyx.acl.service.AdminRoleService;
import com.spyx.acl.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class AdminRoleServiceImpl extends ServiceImpl<AdminRoleMapper, AdminRole>
implements AdminRoleService {

    @Autowired
    private RoleService roleService;


    @Override
    public void saveRole_Admin(Long adminId, Long[] roleId) {
        //1.删除用户原来的角色关系-操作adimin_role表
        baseMapper.delete(new QueryWrapper<AdminRole>().eq("admin_id",adminId));
        //2.将新的角色列表的id保存到admin_role表(批量保存,调取的不是baseMapper层的，而是service层自己的)
        List<AdminRole> rolelist=new ArrayList<AdminRole>();
        for (Long id : roleId) {
            AdminRole adminRole = new AdminRole();
            adminRole.setRoleId(id);
            adminRole.setAdminId(adminId);
            rolelist.add(adminRole);
        }
        this.saveBatch(rolelist);
    }

    @Override
    public Map<String, List> seletRoleList(Integer adminId) {
        //1.查询角色表，中所有的角色表
        List<Role> allRoles = roleService.getAllRoles();

        //2.查询角色和用户的中间表，根据用户id查询用户的角色列表
        QueryWrapper<AdminRole> wrapper = new QueryWrapper<AdminRole>();
        wrapper.eq("admin_id",adminId);
        //2.1 查询Admin_Role表，获取角色id列表
        List<AdminRole> adminRoleList = baseMapper.selectList(wrapper);
        //2.2 从角色id列表中获取角色id,并生成一个新的list
       /* List idlist=new ArrayList();
        for (AdminRole ad : adminRoleList) {
            idlist.add(ad.getRoleId());
        }*/
        List<Long> idList = adminRoleList.stream().map(ad -> ad.getRoleId()).collect(Collectors.toList());
        //2.3 比较所有角色列表和用户所拥有的角色id
        List<Role>  userRoles=new ArrayList<Role>();
        for (Role role : allRoles) {
            for (Long roleid : idList) {
                if(role.getId()==roleid){
                    userRoles.add(role);
                }
            }
        }
        //3.创建一个Map，封装查询出来的所有角色列表和用户自己的角色列表
        Map map=new HashMap();
        map.put("allRolesList",allRoles);//所有角色列表
        map.put("assignRoles",userRoles);//用户自己的角色列表

        return map;
    }
}
